<template>
  <div>
    <el-card class="box-card" style="margin-top:20px">
      <div slot="header" class="clearfix">
        <span>核查填空分数</span>
        <el-button
          type="primary"
          :loading="fullLoading"
          style="float: right;margin-left: 10px;"
          @click="insertThQuesScore"
        >插入答案穷举表
        </el-button>
        <el-select v-model="queryParams.relationSubjectId"
                   style="float: right;"
                   placeholder="请选择科目名称"
                   size="small"
                   @change="getList" clearable>
          <el-option
            v-for="item in subjectList"
            :key="item.value"
            :label="item.text"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="text item">
        <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="科目名称" align="center" prop="subjectName" min-width="100px"/>
          <el-table-column label="题目ID" align="center" prop="quesId"/>
          <el-table-column label="题号" align="center" prop="quesIndex"/>
          <el-table-column label="考生答案" align="center" prop="answer" />
          <el-table-column label="标准答案" align="center" prop="rightAnswer"/>
          <el-table-column label="满分" align="center" prop="fullScore"/>
          <el-table-column label="考生分值" align="center" prop="score"/>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <fail-list :dialogVisibleFu="dialogVisibleFu" :errorData="errorData" @closeDialog="closeDialog"></fail-list>

    <!-- 修改标签配置对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      :before-close="cancel"
      width="500px"
      :close-on-click-modal="true"
      append-to-body
    >
      <el-form ref="editform" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="考生得分：" prop="score">
          <el-input v-model="form.score" placeholder="请输入考生得分" @input="inputValue" @blur="blurValue"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {queryIsOk, getTianKongList, getCalculateScoreList, insertThQuesScores, updateScoreProcess, deleteBatch, updateScore, queryTsinghuaFormalAnswerErr} from "@/api/toolsystem/grade";
  import failList from "@/components/ToolSystem/Grade/failList"
  export default {
    name: "checkGrade",
    components:{
      failList
    },
    data() {
      return {
        // 遮罩层
        loading: false,
        fullLoading: false,
        // 选中数组
        ids: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          relationSubjectId: null, // 学科id
          score: null // 分值
        },
        // 总条数
        total: 0,
        tableList: [], // 表格数据数组
        subjectList: [], // 科目数据数组
        isChecked: false, // 防重复点击
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 表单参数
        form: {
          score: null
        },
        maxScore: null,// 最大分数（满分）
        // 表单校验
        rules: {
          score: [
            {
              required: true,
              message: "请输入考生得分",
              trigger: "blur"
            }
          ],
        },
        dialogVisibleFu: false, // 控制弹框显示与隐藏
        errorData:[], // 错误数据表格
        percentage: 0,// 上传进度
        timerProcess: null,// 进度定时器
        timerError: null,// 错误请求定时器
      };
    },
    watch:{
      percentage(value){
        if(this.percentage==100){
          this.getList();
          this.fullLoading = false;
          setTimeout(()=>{
            this.$root.globalDialog = false;
          }, 2000)
          clearInterval(this.timerError);
          clearInterval(this.timerProcess);
          this.msgSuccess('插入完成')
        }
      }
    },
    created() {
      this.getSubjectList()
      this.getList();
    },
    methods: {
      filterSubject(value, row){
        return row.relationSubjectId == value;
      },
      filterScore(value, row, column) {
        const property = column['property'];
        return row[property] == value;
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.form = {
          score: "",
        };
        this.$refs["editform"].resetFields();
      },
      /** 修改提交按钮 */
      submitForm() {
        this.$refs["editform"].validate(valid => {
          if (!valid) return;
          if(this.form.score){
            this.form.score = Number(this.form.score)
          }
          updateScore(this.form)
            .then(response => {
              if (response.code != 200) return this.msgError(response.msg);
              this.msgSuccess(response.msg);
              this.cancel();
              this.getList();
            })
            .catch(error => {
              console.log(error);
            });
        });
      },
      // 考生得分输入框内容限制
      blurValue(){
        if(this.form.score){
          this.form.score = Number(this.form.score)
        }
      },
      // 考生得分输入框内容限制
      inputValue(value){
        let isDot = value.toString().indexOf(".") != -1?true:false// 是否含有小数点
        let score = null;
        let one = null;//输入值的第一位
        let two = null;//输入值的第二位
        let lf = null;//小数点左边的数
        let rt = null;//小数点右边的数

        if(value.length==1){
          score = value.replace(/[^\d]/g,'')
        }else if(value.length>1){
          one = value.slice(0,1);
          two = value.slice(1,2);
          // 如果第一位数是 0 ，那么第二位必须是 . 或者为空
          // 如果第一位数不是 0 ，那么判断是否含有小数点
          // -- 有小数点，接下来输入值不可以有小数点，小数点右边的数做限制
          // -- 没有小数点，接下来输入值可以有小数点
          if(one == 0 && two!='.'){
            score = one
          }else if((one == 0 && two=='.') || (one!=0 && isDot)){
            lf=value.split('.')[0]
            rt=value.split('.')[1].slice(0,1)
            score = lf + '.' + rt.replace(/[^\d]/g,'')
          }else{
            score = value.replace(/[^\d.]/g,'')
          }
        }
        // 输入值不能超过满分
        if(score <= this.maxScore){
          this.form.score = score
        }else{
          this.form.score = this.maxScore
        }
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        console.log(row)
        this.form = {
          id: row.id,
          score: row.score
        };
        this.maxScore = Number(row.fullScore)
        this.open = true;
        this.title = "考生分值";
      },
      getSubjectList() {
        getCalculateScoreList()
          .then(response => {
            if (response.code != 200) {
              return;
            }
            let dataList = response.data
            dataList.forEach(item=>{
              let obj = {
                text: item['name'],
                value: item['relationSubjectId']
              }
              this.subjectList.push(obj)
            })
          })
          .catch(error => {
            console.log(error);
          });
      },
      /** 查询填空题列表 */
      getList() {
        this.loading = true;
        getTianKongList(this.queryParams)
          .then(response => {
            if (response.code != 200) {
              this.loading = false;
              return this.msgError(response.msg);
            }
            this.tableList = response.rows;
            this.total = response.total;
            if (this.tableList.length <= 0) {
              this.$alert('未找到填空题答案，请联系相关人员。', "结果提示");
            }
            this.loading = false;
          })
          .catch(error => {
            this.loading = false;
            console.log(error);
          });
      },
      // 关闭弹框
      closeDialog(val){
        this.dialogVisibleFu = val
      },
      // 插入答案穷举表
      insertThQuesScore() {
        this.$confirm('是否插入答案穷举表?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let status = await this.queryIsOk()
          if(!status){
            return;
          }
          this.fullLoading = true;
          this.percentage = 0
          this.$root.percentage = 0
          this.$root.globalDialog = true
          insertThQuesScores()
          this.timerProcess = setInterval(()=>{
            this.updateScoreProcess();
          }, 10000)
          this.timerError = setInterval(()=>{
            this.queryScoreAnswerErr();
          }, 10000)
        }).catch(() => {
          this.msgInfo('已取消插入')
        });
      },
      // 插入答案穷举表-查询进度
      updateScoreProcess(){
        updateScoreProcess().then(response => {
          console.log(response)
          if (response.code != 200) {
            return;
          }
          this.percentage = Number(response.data);
          this.$root.percentage = Number(response.data);
        }).catch(error=>{
          console.log(error);
        })
      },
      // 插入答案穷举表-插入答案穷举表错误
      queryScoreAnswerErr(){
        queryTsinghuaFormalAnswerErr().then(response => {
          console.log(response)
          if (response.code != 200) {
            return;
          }
          if(response.data){
            clearInterval(this.timerError);
            clearInterval(this.timerProcess);
            this.fullLoading = false
            this.$root.globalDialog = false
            this.errorData = response.data;
            this.dialogVisibleFu = true;
          }
        }).catch(error=>{
          console.log(error)
        })
      },
      // 查询是否可以执行,true可通行； false不可通行
      queryIsOk(){
        return queryIsOk()
          .then(res=>{
            if(res.code != 200){
              return false;
            }
            if(res.data.isOk){
              return true;
            }else{
              this.msgInfo(res.data.msg)
              return false;
            }
          })
          .catch(error=>{
            console.log(error)
            return false;
          })

      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
      },
    }
  };
</script>

<style scoped lang="scss">
  ::v-deep .el-card .el-card__header {
    line-height: 36px !important;
  }
  .el-select{
    width: 200px;
  }
  ::v-deep .el-loading-spinner {
    position: absolute;
    top: 20% !important;
  }
</style>
